# -*- coding: utf-8 -*-

from __future__ import unicode_literals

from django.http import HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.conf import settings
from django.shortcuts import render_to_response

from accounts.models import Profile
from index.models import State

from urllib import urlencode
import requests
import json


def wechat_qrcode(request):
    state = request.GET.get('state', '')

    redirect_uri = '{0}/third/guming/wechat/open/callback/'.format(settings.BASE_HOST)
    redirect_url = urlencode({'redirect_uri': redirect_uri})

    url = 'https://open.weixin.qq.com/connect/qrconnect?appid={0}&{1}&response_type=code&scope=snsapi_login&state={2}#wechat_redirect'.format(
        settings.WECHAT_OPEN_APPID, redirect_url, state)
    return redirect(url)


def wechat_mp(request):
    state = request.GET.get('state', '')

    redirect_uri = '{0}/third/wechat/oauth/callback/'.format(settings.BASE_HOST)
    redirect_url = urlencode({'redirect_uri': redirect_uri})

    url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&{1}&response_type=code&scope=snsapi_userinfo&state={2}#wechat_redirect'.format(
        settings.wechat_mp_appid, redirect_url, state)
    return redirect(url)


def wechat_open_callback(request):
    code = request.GET.get('code', '')
    state = request.GET.get('state', '')

    state_m = State.objects.filter(code=state).first()

    if not state_m:
        return JsonResponse(dict(
            errcode=-1,
            errmsg='invalid state code'
        ))

    action = state_m.action

    url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
    params = dict(
        appid=settings.WECHAT_OPEN_APPID,
        secret=settings.WECHAT_OPEN_APPSECRET,
        code=code,
        grant_type='authorization_code'
    )
    ret = requests.get(url, params)
    data = ret.json()
    access_token = data.get('access_token', '')
    openid = data.get('openid', '')

    if action == 'signin':
        profile = Profile.objects.filter(openid_open=openid).first()
        if not profile:
            return JsonResponse(dict(
                errcode=-1,
                errmsg='not found profile, need to bind'
            ))

        user = profile.user
        state_m.user = user
        state_m.is_valid = True
        state_m.save()
        errcode = 0
        return render_to_response('third/open_callback.html', locals())

    elif action == 'bind':
        user = state_m.user

        profile = Profile.objects.filter(user=user).first()
        if not profile:
            profile = Profile(user=user, openid_open=openid)
            profile.save()
        else:
            profile.openid_open = openid
            profile.save()
        state_m.is_valid = True
        state_m.save()
        errcode = 0
        return render_to_response('third/open_callback.html', locals())

    return JsonResponse(dict(
        errcode=-1,
        errmsg='invalid action'
    ))


def wechat_mp_callback(request):
    code = request.GET.get('code', '')
    state = request.GET.get('state', '')

    state_m = State.objects.filter(code=state).first()

    if not state_m:
        return JsonResponse(dict(
            errcode=-1,
            errmsg='invalid state code'
        ))

    action = state_m.action

    url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
    params = dict(
        appid=settings.WECHAT_MP_APPID,
        secret=settings.WECHAT_MP_APPSECRET,
        code=code
    )
    ret = requests.get(url, params)
    data = ret.json()
    access_token = data.get('access_token', '')
    openid = data.get('openid', '')

    if action == 'signin':
        profile = Profile.objects.filter(openid_mp=openid).first()
        if not profile:
            return JsonResponse(dict(
                errcode=-1,
                errmsg='not found profile, need to bind'
            ))

        user = profile.user
        state_m.user = user
        state_m.is_valid = True
        state_m.save()
        return JsonResponse(dict(
            errcode=0
        ))

    elif action == 'bind':
        user = state_m.user

        profile = Profile.objects.filter(user=user).first()
        if not profile:
            profile = Profile(user=user, openid_mp=openid)
            profile.save()
        else:
            profile.openid_mp = openid
            profile.save()
        state_m.is_valid = True
        state_m.save()
        return JsonResponse(dict(
            errcode=0
        ))

    return JsonResponse(dict(
        errcode=-1,
        errmsg='invalid action'
    ))


def dingtalk_qrcode(request):
    state = request.GET.get('state', '')

    redirect_uri = '{0}/third/dingtalk/callback/'.format(settings.BASE_HOST)

    redirect_url = urlencode({'redirect_uri': redirect_uri})

    url = 'https://oapi.dingtalk.com/connect/qrconnect?appid={0}&response_type=code&scope=snsapi_login&state={1}&{2}'.format(
        settings.DINGTALK_APPID, state, redirect_url)
    return redirect(url)


def dingtalk_oauth(request):
    state = request.GET.get('state', '')

    redirect_uri = '{0}/third/dingtalk/callback/'.format(settings.BASE_HOST)

    redirect_url = urlencode({'redirect_uri': redirect_uri})

    url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid={0}&response_type=code&scope=snsapi_login&state={1}&{2}'.format(
        settings.DINGTALK_APPID, state, redirect_url)
    return redirect(url)


def dingtalk_isv(request):
    domain = request.GET.get('domain', '')
    return HttpResponse('dingtalk_isv')


def dingtalk_callback(request):
    code = request.GET.get('code', '')
    state = request.GET.get('state', '')

    ret = requests.get('https://oapi.dingtalk.com/sns/gettoken?appid={0}&appsecret={1}'.format(settings.DINGTALK_APPID,
                                                                                               settings.DINGTALK_APPSECRET))
    data = ret.json()

    access_token = data.get('access_token', '')

    ret = requests.post('https://oapi.dingtalk.com/sns/get_persistent_code?access_token={0}'.format(access_token),
                        data=json.dumps(dict(tmp_auth_code=code)))
    data = ret.json()

    openid = data.get('openid', '')
    persistent_code = data.get('persistent_code', '')
    unionid = data.get('unionid', '')

    return JsonResponse(dict(
        errcode=-1
    ))
